package model

import (
	"errors"

	"github.com/google/uuid"
	"github.com/jinzhu/gorm"
)

// FileInfo represents a Upload info
type FileInfo struct {
	gorm.Model
	Name    string    `json:"name"`
	MD5Name string    `json:"md5name"`
	URL     string    `json:"url"`
	UUID    uuid.UUID `json:"uuid"`
}

// AddNewUpload add a new Upload
func AddNewUpload(fileInfo *FileInfo) (interface{}, error) {

	GenUUID, err := uuid.NewUUID()
	if err != nil {
		return nil, err
	}
	fileInfo.UUID = GenUUID
	file := db.Save(fileInfo)

	return file.Value, nil

}

// GetUpload get a single Upload
func GetUpload(UploadID string) (*FileInfo, error) {
	var Upload FileInfo
	// SELECT * FROM Upload WHERE id = UploadID;
	db.First(&Upload, UploadID)
	if Upload.ID == 0 {
		err := errors.New("no Upload found")
		return &FileInfo{}, err
	}
	result := FileInfo{
		Name:    Upload.Name,
		MD5Name: Upload.MD5Name,
		URL:     Upload.URL,
		UUID:    Upload.UUID,
	}

	return &result, nil
}

// ExistUploadByName check the name is exist or not
func ExistUploadByName(name string) bool {
	var myUpload FileInfo
	db.Select("id").Where("name = ?", name).First(&myUpload)
	if myUpload.ID > 0 {
		return true
	}
	return false
}

// UpdateUpload edit file info
func UpdateUpload(id int, data interface{}) bool {
	db.Model(&FileInfo{}).Where("id = ?", id).Updates(data)

	return true
}

// DeleteUpload delete the file info from db
func DeleteUpload(id int) bool {
	db.Where("id = ?", id).Delete(&FileInfo{})

	return true
}

// GetAllUploads get the all Uploads info from db
func GetAllUploads() (result []FileInfo, err error) {
	var myUpload []FileInfo
	db.Find(&myUpload)

	if len(myUpload) == 0 {
		err = errors.New("no Upload found")
		return nil, err
	}
	return myUpload, nil
}

// GetFileInfoWithName get a single file info by name
func GetFileInfoWithName(name string) (*FileInfo, error) {
	var filesInfo FileInfo

	db.Where("md5_name = ?", name).Find(&filesInfo)
	if filesInfo.ID == 0 {
		err := errors.New("no file info found")
		return &FileInfo{}, err
	}
	result := FileInfo{
		Model: gorm.Model{
			ID: filesInfo.ID,
		},
		Name:    filesInfo.Name,
		MD5Name: filesInfo.MD5Name,
		URL:     filesInfo.URL,
		UUID:    filesInfo.UUID,
	}

	return &result, nil
}
